//
//  GFDetialCollectionViewCell.m
//  GoodFood
//
//  Created by dllo on 15/10/31.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFDetialCollectionViewCell.h"

@interface GFDetialCollectionViewCell ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *detialTableView;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSMutableArray *tempArr;
@property (nonatomic, strong) GFWaitView *waitView;
@property (nonatomic, strong) AppDelegate *app;
@end

@implementation GFDetialCollectionViewCell

-(void)handelDataForCell {
    self.app = [[UIApplication sharedApplication] delegate];
    NSString *url = [NSString stringWithFormat:@"http://api.meishixing.com/tweet/tweet/detail/session_id=%@&tweet_id=%@",self.app.session_id, self.tweetID];
    
    [AFNetHandle GETWithURL:url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        self.tempArr = [NSMutableArray array];
        GFDetialModel *model = [GFDetialModel modWithDic:[result objectForKey:@"result"]];
        [self.tempArr addObject:model];
        [self.detialTableView reloadData];
        [self.waitView removeFromSuperview];
        
    } fail:^(NSError *error) {
        
    }];
    
    
}

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.titleArray = @[@"在这里可以吃到", @"他们也喜欢", @"评论"];
        self.detialTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
        self.detialTableView.backgroundColor = [UIColor colorWithRed:0.841 green:0.814 blue:0.860 alpha:1.000];
        self.detialTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.detialTableView.delegate = self;
        self.detialTableView.dataSource = self;
        self.detialTableView.showsVerticalScrollIndicator = NO;
        self.detialTableView.tableFooterView = [[UIView alloc] init];
        [self.contentView addSubview:self.detialTableView];
        
        [self.detialTableView registerClass:[GFDetialTableViewCell class] forCellReuseIdentifier:@"detial"];
        [self.detialTableView registerClass:[GFCommentsTableViewCell class] forCellReuseIdentifier:@"comments"];
        [self.detialTableView registerClass:[GFLikeUserTableViewCell class] forCellReuseIdentifier:@"likeUser"];
        [self.detialTableView registerClass:[GFNoLikeTableViewCell class] forCellReuseIdentifier:@"noLike"];
        self.waitView = [[GFWaitView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return self;
}

-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    
    self.detialTableView.contentOffset = CGPointZero;

}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if (0 == section) {
        return nil;
    } else {
        
        return self.titleArray[section - 1];
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GFDetialModel *model = [self.tempArr lastObject];
    if (0 == indexPath.section) {
        return ScreenWidth - 20;
    } else if (2 == indexPath.section) {
        
        if (model.like_user_list.count == 0) {
            return 44;
        } else {
            return [GFLikeUserTableViewCell heightForLikeUserImageView:model.like_user_list.count] + 10;
        } 
    } else if (3 == indexPath.section) {
        NSArray *arr = model.comments;
        if (model.comments.count == 0) {
            return 44;
        } else {
        NSDictionary *dic = [arr objectAtIndex:indexPath.row];
        CGRect height = [dic[@"comment"] boundingRectWithSize:CGSizeMake(ScreenWidth - (ScreenWidth / 10 + 30), 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
        return height.size.height + 20 + ScreenWidth / 20;
        }
        
    } else {
        return 44;
    }
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    GFDetialModel *model = [self.tempArr lastObject];
    if (1 == section) {
        if ([model.phone isEqualToString:@""]) {
            return 1;
        } else {
            return 2;
        }
    } else if (3 == section) {
        
        if (model.comments.count == 0) {
            return 1;
        } else {
            return model.comments.count;
        }
    } else {
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GFDetialModel *model = [self.tempArr lastObject];
    if (0 == indexPath.section) {
        
        GFDetialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detial"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        cell.block = self.block;
        return cell;
        
    } else if (1 == indexPath.section) {
        if (0 == indexPath.row) {
            static NSString *str = @"table";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"table"];
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.imageView.image = [UIImage imageNamed:@"iconfont-location2"];
            cell.textLabel.text = model.place_name;
            cell.detailTextLabel.text = model.address;
            return cell;
            
        } else {
            
            static NSString *str1 = @"table";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str1];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"table"];
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.imageView.image = [UIImage imageNamed:@"iconfont-dianhua-2"];
            if (![model.phone containsString:@";"]) {
                NSArray *phoneArr = [model.phone componentsSeparatedByString:@" "];
                cell.textLabel.text = phoneArr[0];
            } else {
                NSArray *phoneArr = [model.phone componentsSeparatedByString:@";"];
                cell.textLabel.text = phoneArr[0];
            }
            return cell;
        }
    } else if (2 == indexPath.section) {
        
        if (model.like_user_list.count == 0) {
            GFNoLikeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noLike"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.str = @"暂时无人喜欢";
            return cell;
        } else {
            GFLikeUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"likeUser"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.likeUserArr = model.like_user_list;
            return cell;
        }
    } else {
        
        if (model.comments.count == 0) {
            GFNoLikeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noLike"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.str = @"暂时无人评论";
            return cell;
        } else {
            GFCommentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"comments"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.tempDic = [model.comments objectAtIndex:indexPath.row];
            return cell;
        }
    }
}

-(void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.textLabel.textColor = [UIColor redColor];
        cell.detailTextLabel.textColor = [UIColor redColor];
    
}

-(void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.textColor = [UIColor blackColor];
}

#pragma mark - 找到vc
- (UIViewController*)viewController {
    for (UIView *next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GFDetialModel *model = [self.tempArr lastObject];
    if (1 == indexPath.section) {
        if (0 == indexPath.row) {
            GFResturtantDetialViewController *resturtantVC = [[GFResturtantDetialViewController alloc] initWithId:[model.place_id integerValue] withSession:self.app.session_id];
            UIViewController *VC = [self viewController];
            
            [VC.navigationController pushViewController:resturtantVC animated:YES];
            
        } else {
            
            NSMutableArray *array = [self phoneNumberSub];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"拨打电话" preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            for (int i = 0; i < array.count; i ++) {
                UIAlertAction *action = [UIAlertAction actionWithTitle:array[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self phoneCallWithTel:array[i]];
                }];
                [alert addAction:action];
            }
            [alert addAction:actionCancel];
            UIViewController *vc = [self viewController];
            [vc presentViewController:alert animated:1 completion:nil];
            
        }
    } else if (2 == indexPath.section) {
        
        GFLikeFoodViewController *likeFoodVC = [[GFLikeFoodViewController alloc] init];
        likeFoodVC.tempArr = model.like_user_list.mutableCopy;
        UIViewController *VC = [self viewController];
        [VC.navigationController pushViewController:likeFoodVC animated:YES];
    }
    
}

#pragma mark - 电话号拆分
- (NSMutableArray *)phoneNumberSub {
    NSInteger i = 0;
    GFDetialModel *model = [self.tempArr lastObject];
    if ([model.phone containsString:@";"]) {
        i = 1;
    } else if ([model.phone containsString:@" "]) {
        i = 2;
    }
    NSMutableArray *array = [NSMutableArray array];
    if (0 == i) {
        [array addObject:model.phone];
    } else if (1 == i) {
        NSArray *array1 = [model.phone componentsSeparatedByString:@";"];
        for (int i = 0; i < array1.count; i ++) {
            [array addObject:array1[i]];
        }
    } else if (2 == i) {
        NSArray *array2 = [model.phone componentsSeparatedByString:@" "];
        for (int i = 0; i < array2.count; i ++) {
            if (![array2[i] isEqualToString:@""]) {
                [array addObject:array2[i]];
            }
        }
    }
    return array;
    
}
#pragma mark - 拨打电话
- (void)phoneCallWithTel:(NSString *)tel {
    //    UIWebView *webView = nil;
    //    if (webView == nil) {
    //        webView = [[UIWebView alloc] init];
    //    }
    //    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", tel]];
    //    NSLog(@"%@",url);
    //    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    [webView loadRequest:request];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", tel]];
    
    [[UIApplication sharedApplication] openURL:url];
}

-(void)setTweetID:(NSNumber *)tweetID {
    
    if (_tweetID != tweetID) {
        _tweetID = tweetID;
    }
    
    [self.contentView addSubview:self.waitView];
    [self handelDataForCell];

}

@end
